#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include "Log.hpp"
using namespace LogModule;

const std::string defaultdict = "./dictionary.txt";
const std::string sep = ":";
class Dict
{
private:
    std::string _dict_path = defaultdict; // 路径加文件名
    std::unordered_map<std::string, std::string> _dict;

public:
    Dict(const std::string &path = defaultdict) : _dict_path(path)
    {
    }
    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "打开字典错误:" << _dict_path << " 错误";
            return false;
        }

        // 打开成功
        std::string line;
        while (std::getline(in, line))
        {
            // code:代码
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析:" << line << "失败";
                continue;
            }
            // 读取成功
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "没有有效内容" << line << "NONE";
            }
            _dict.insert(std::make_pair(english, chinese));
            LOG(LogLevel::DEBUG) << "加载:" << line;
        }
        in.close();
        return true;
    }
    std::string Translate(const std::string &word, InertAddr &client)
    {
        LOG(LogLevel::DEBUG) << "进入到了翻译模块" << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word;
        auto iter = _dict.find(word);
        if (iter == _dict.end())
            return "None";
        return iter->second;
    }

    ~Dict()
    {
    }
};
